package com.pro01.backend.service;

import com.pro01.backend.dto.MessageDTO;
import com.pro01.backend.mapper.MessageMapper;
import com.pro01.backend.pojo.Message;
import com.pro01.backend.pojo.MessageConversation;
import com.pro01.backend.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private NotificationService notificationService;

    // 发送私信
    public void sendMessage(Message message) {
        message.setStatus("UNREAD"); // 初始为未读
        int result = messageMapper.insertMessage(message);
        if (result == 0) {
            throw new RuntimeException("发送私信失败");
        }

        // ✅ 发送通知
        String link = "/messages/conversation/" + message.getSenderId();  // 点击跳到和发送者的聊天页
        notificationService.sendNotification(
                message.getReceiverId(), // 收件人（接收通知的人）
                message.getSenderId(),   // 发件人（通知发送者）
                "PRIVATE_MESSAGE",       // 通知类型
                "你收到了一条新私信",       // 通知内容
                link                     // 通知跳转链接
        );
    }

    // 查询收件箱
    public PageResult<Message> getReceivedMessages(Long receiverId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<Message> records = messageMapper.selectReceivedMessages(receiverId, offset, pageSize);
        int total = messageMapper.countReceivedMessages(receiverId);
        return new PageResult<>(total, records);
    }

    // 查询发件箱
    public PageResult<Message> getSentMessages(Long senderId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<Message> records = messageMapper.selectSentMessages(senderId, offset, pageSize);
        int total = messageMapper.countSentMessages(senderId);
        return new PageResult<>(total, records);
    }

    // 标记已读
    public void markAsRead(Long messageId, Long receiverId) {
        int result = messageMapper.markMessageAsRead(messageId, receiverId);
        if (result == 0) {
            throw new RuntimeException("标记已读失败，可能该消息不存在、不是你的，或已读过了");
        }
    }

    // 删除私信
    public void deleteMessage(Long messageId, Long userId) {
        int result = messageMapper.deleteMessage(messageId, userId);
        if (result == 0) {
            throw new RuntimeException("删除失败，可能该消息不存在、已删除，或者无权限删除");
        }
    }

    // 查询未读消息数量
    public int getUnreadCount(Long receiverId) {
        return messageMapper.countUnreadMessages(receiverId);
    }

    // 会话列表
    public PageResult<MessageConversation> getConversations(Long userId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        // 1. 查询所有会话基础信息
        List<MessageConversation> conversations = messageMapper.selectConversations(userId, offset, pageSize);

        // 2. 遍历每个会话，查出最新的消息内容
        for (MessageConversation conv : conversations) {
            if (conv.getLastMessageId() != null) {
                String content = messageMapper.getContentByMessageId(conv.getLastMessageId());
                conv.setLastMessageContent(content);
            }
        }

        // 3. 查询总会话数量
        int total = messageMapper.countConversations(userId);

        return new PageResult<>(total, conversations);
    }

    // 拉取与对方的聊天记录
//    public PageResult<Message> getConversation(Long userId, Long otherUserId, int pageNum, int pageSize) {
//        int offset = (pageNum - 1) * pageSize;
//        List<Message> records = messageMapper.selectConversation(userId, otherUserId, offset, pageSize);
//        int total = messageMapper.countConversation(userId, otherUserId);
//        return new PageResult<>(total, records);
//    }
    public PageResult<MessageDTO> getConversation(Long userId, Long otherUserId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<MessageDTO> records = messageMapper.selectConversationDTO(userId, otherUserId, offset, pageSize);
        int total = messageMapper.countConversation(userId, otherUserId);
        return new PageResult<>(total, records);
    }

    // 初始化聊天
    public void initConversationIfAbsent(Long userId1, Long userId2) {
        if (userId1.equals(userId2)) {
            throw new RuntimeException("不能和自己建立私信会话");
        }

        int count = messageMapper.countConversationExists(userId1, userId2);
        if (count == 0) {
            // 插入一条系统消息：非展示内容，仅用于初始化会话
            messageMapper.insertSystemMessage(userId1, userId2, "[私信会话已建立]");
        }
    }


}
